<template>
  <div class="user-list">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.email" placeholder="请输入email" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.tel" placeholder="请输入手机" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <i class="el-icon-search"></i> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="table-card">
      <div class="operation-bar">
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedUsers.length">
          <i class="el-icon-delete"></i> 批量删除
        </el-button>
        <el-button type="primary" @click="handleAdd">
          <i class="el-icon-plus"></i> 添加用户
        </el-button>
      </div>

      <!-- 用户表格 -->
      <el-table
        :data="paginatedData"
        border
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="编号" type="index" width="80"></el-table-column>
        <el-table-column prop="email" label="Email" width="180"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="sex" label="性别" width="80"></el-table-column>
        <el-table-column prop="tel" label="手机" width="120"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template v-slot="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '已启用' : '已拉黑' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400" fixed="right">
          <template v-slot="{ row }">
            <el-button
              :type="row.status === 1 ? 'danger' : 'success'"
              size="mini"
              @click="handleStatusChange(row)"
            >
              {{ row.status === 1 ? '拉黑' : '启用' }}
            </el-button>
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(row)"
              icon="el-icon-edit"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              size="mini"
              @click="handlePassword(row)"
              icon="el-icon-key"
            >
              改密
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="handleDelete(row)"
              icon="el-icon-delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px">
        <el-form-item label="Email" prop="email">
          <el-input v-model="userForm.email" :disabled="dialogType === 'edit'"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机" prop="tel">
          <el-input v-model="userForm.tel"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="userForm.address"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPassword">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'UserList',
  data() {
    // ���确认校验
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    return {
      // 搜索表单
      searchForm: {
        username: '',
        email: '',
        tel: ''
      },
      // 表格数据
      tableData: [],
      loading: false,
      selectedUsers: [],
      
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      },
      
      // 对话框
      dialogVisible: false,
      dialogType: 'add', // 'add' 或 'edit'
      dialogTitle: '添加用户',
      userForm: {
        email: '',
        username: '',
        sex: '男',
        tel: '',
        address: ''
      },
      
      // 表单校验规则
      rules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请���择性别', trigger: 'change' }
        ],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ]
      },
      
      // 修改密码
      passwordDialogVisible: false,
      passwordForm: {
        email: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  
  created() {
    this.fetchData()
  },
  
  computed: {
    // 计算分页后的数据
    paginatedData() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      return this.tableData.slice(start, end);
    }
  },
  
  methods: {
    // 获取用户列表数据
    async fetchData() {
      this.loading = true;
      try {
        const params = {
          username: this.searchForm.username || '',
          email: this.searchForm.email || '',
          tel: this.searchForm.tel || ''
        };
        const res = await request.get('/FindAllUserServlet', { params });
        
        if (res.code === 0) {
          const data = res.data;
          this.tableData = data.records.map(user => ({
            ...user,
            status: user.status || 1
          }));
          this.pagination.total = data.total;
        } else {
          this.$message.error(res.msg || '获取用户列表失败');
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$message.error('获取用户列表失败');
      }
      this.loading = false;
    },

    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        username: '',
        email: '',
        tel: ''
      }
      this.handleSearch()
    },

    // 表格选择
    handleSelectionChange(selection) {
      this.selectedUsers = selection
    },

    // 批量删除
    handleBatchDelete() {
      if (!this.selectedUsers.length) return
      
      this.$confirm('确认要删除选中的用户吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const emails = this.selectedUsers.map(user => user.email).join(',')
          await request.get('/SelectDelServlet', {
            params: { emails }
          })
          this.$message.success('批量删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('批量删除失败')
        }
      })
    },

    // 添加用户
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTitle = '添加用户'
      this.userForm = {
        email: '',
        username: '',
        sex: '男',
        tel: '',
        address: ''
      }
      this.dialogVisible = true
    },

    // 编辑用户
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTitle = '编辑用户'
      this.userForm = { ...row }
      this.dialogVisible = true
    },

    // 提交表单
    async submitForm() {
      try {
        // 表单验证
        await this.$refs.userForm.validate()
        
        if (this.dialogType === 'add') {
          // 添加用户前先检查邮箱是否可用
          const checkRes = await request.get('/CheckEmailServlet', {
            params: { email: this.userForm.email }
          })
          
          if (checkRes.data === true) {
            this.$message.error('该邮箱已被使用')
            return
          }
          
          // 调用注册接口
          const res = await request.post('/RegisterServlet', {
            ...this.userForm,
            password: '123456' // 设置默认密码
          })
          
          if (res.code === 0) {
            this.$message.success('添加成功')
            this.dialogVisible = false
            this.fetchData()
          } else {
            this.$message.error(res.msg || '添加失败')
          }
        } else {
          // 编辑用户
          await request.get('/UpdateUserInfoServlet', {
            params: {
              email: this.userForm.email,
              username: this.userForm.username,
              sex: this.userForm.sex,
              tel: this.userForm.tel,
              address: this.userForm.address
            }
          })
          this.$message.success('更新成功')
          this.dialogVisible = false
          this.fetchData()
        }
      } catch (error) {
        console.error('操作失败:', error)
        this.$message.error(this.dialogType === 'add' ? '添加失败' : '更新失败')
      }
    },

    // 修改密码
    handlePassword(row) {
      this.passwordForm = {
        email: row.email,
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      this.passwordDialogVisible = true
    },

    // 提交密码修���
    async submitPassword() {
      try {
        // 表单验证
        await this.$refs.passwordForm.validate()
        
        // 验证旧密码
        const checkRes = await request.get('/CheckPwdServlet', {
          params: {
            email: this.passwordForm.email,
            oldPwd: this.passwordForm.oldPassword
          }
        })
        
        if (checkRes.code === 0 && checkRes.data === true) {
          // 修改新密码
          const res = await request.get('/ChangePwdServlet', {
            params: {
              email: this.passwordForm.email,
              pwd: this.passwordForm.newPassword
            }
          })
          
          if (res.code === 0) {
            this.$message.success('密码修改成功')
            this.passwordDialogVisible = false
          } else {
            this.$message.error(res.msg || '密码修改失败')
          }
        } else {
          this.$message.error('原密码错误')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        this.$message.error('密码修改失败')
      }
    },

    // 更改用户状态
    async handleStatusChange(row) {
      try {
        const confirmText = row.status === 1 ? '确认要拉黑该用户吗？' : '确认要启用该用户吗？';
        await this.$confirm(confirmText, '提示', {
          type: 'warning'
        });

        const newStatus = row.status === 1 ? -1 : 1;
        console.log('修改状态 - 当前状态:', row.status, '新状态:', newStatus);

        const res = await request.get('/ChangeStatusServlet', {
          params: {
            email: row.email,
            status: newStatus
          }
        });

        console.log('修改状态响应:', res);

        if (res.code === 0) {
          // 使用服务器返回的数据更新状态
          if (res.data) {
            row.status = res.data.status;
          } else {
            row.status = newStatus;
          }
          this.$message.success(res.msg);
          // 刷新列表数据
          this.fetchData();
        } else {
          this.$message.error(res.msg || '状态修改失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('状态修改失败:', error);
          this.$message.error('状态修改失败');
        }
      }
    },

    // 删除用户
    handleDelete(row) {
      this.$confirm('确认要删除该用户吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await request.get('/DelUserByEmailServlet', {
            params: { email: row.email }
          })
          this.$message.success('删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },

    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1; // 重置到第一页
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
    }
  }
}
</script>

<style lang="less" scoped>
.user-list {
  .search-card {
    margin-bottom: 20px;
  }

  .operation-bar {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 